package it.pir.es10ChatWS;

import java.io.*;
import java.util.*;

public class Client {

	private String user;
	private Connection connection;
	
	public Client(String url, String user) {
		this.user=user;
	}

	private void run() throws IOException {
		String text;
		
		InputStreamReader in = new InputStreamReader(System.in);
		BufferedReader bIn = new BufferedReader(in);
		
		while(true){
			text = bIn.readLine();
			char first = text.length()>0 ? text.charAt(0) : '\0';
			
			if(first!='@') { // invio in modalità normale
				Message m = new Message(text, user);
				connection.send(m.getText());
			} else if(text.length()==1) { // richiesta lista utenti connessi
				List<String> users=connection.getUsers();
				System.out.print("Utenti connessi:");
				for(String user: users)
					System.out.print(user+" ");
				System.out.println();
			} else { // messaggio privato
				int space=text.indexOf(' ');
				if(space<0) {
					System.out.println("ERRORE FORMATO!!");
				} else {
					String to=text.substring(1,space);
					text=text.substring(space+1);
					Message message= new Message(text,user);
					connection.sendPrivate(message.getText(), to);
				}
			}
		}
	}
	
	public static void main(String args[]) {
		Client client=new Client(args[0], args[1]);
		try {
			client.run();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
